package com.wjh.graduation.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wjh.graduation.domain.Budget;
import com.wjh.graduation.domain.R;
import com.wjh.graduation.service.BudgetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Wu Jiahong
 * @since 2022-02-03
 */
@RestController
@RequestMapping("/budget")
@Api(tags = "预算有关的接口")
public class BudgetController {

	@Autowired
	BudgetService budgetService;

	@ApiOperation("获得预算")
	@GetMapping("/getBudget")
	public R<Budget> getBudget(@RequestParam @ApiParam("传入用户Id") Integer userId) {
		QueryWrapper<Budget> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		Budget budget = budgetService.getOne(queryWrapper);
		if (budget != null) {
			return new R<Budget>(200, budget, "获取成功");
		} else {
			return new R<Budget>(303, "获取失败");
		}
	}


	@ApiOperation("添加预算")
	@PostMapping("/create")
	@Transactional
	public R creatBudget(@Validated @RequestBody @ApiParam(name = "传入预算金额、用户ID") Budget budget) {
		QueryWrapper<Budget> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", budget.getUserId());
		if (budgetService.getOne(queryWrapper) != null) {
			return new R(303, "已存在预算，请勿重新添加");
		}
		if (budgetService.save(budget)) {

			Budget one = budgetService.getOne(queryWrapper);
			if (one != null) {
				return new R(200, one, "添加成功");
			} else {
				throw new NullPointerException();
			}
		} else {
			return new R(303, "添加失败");
		}
	}

	@ApiOperation("删除预算")
	@GetMapping("/delete")
	public R deleteGroup(@ApiParam("传入预算的的ID") @RequestParam Integer id) {
		if (budgetService.removeById(id)) {
			return new R(200, "删除成功");
		} else {
			return new R(303, "删除失败");
		}
	}

	@ApiOperation("修改预算")
	@PostMapping("/update")
	@Transactional
	public R updateGroup(@Validated @ApiParam(name = "传入预算金额、用户ID") @RequestBody Budget budget) {
		if (budgetService.updateById(budget)) {
			QueryWrapper<Budget> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("user_id", budget.getUserId());
			Budget one = budgetService.getOne(queryWrapper);
			if (one != null) {
				return new R(200, one, "修改成功");
			} else {
				throw new NullPointerException();
			}
		} else {
			return new R(303, "修改失败");
		}
	}
}

